package com.chushouya.manager.service.common.impl;

import com.chushouya.manager.dao.entity.RegionEntity;
import com.chushouya.manager.dao.repository.RegionRepository;
import com.chushouya.manager.dto.admin.region.RegionQuery;
import com.chushouya.manager.dto.admin.region.RegionTreeDTO;
import com.chushouya.manager.service.common.RegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RegionServiceImpl implements RegionService {

    @Resource
    private RegionRepository regionRepository;

    @Override
    public List<RegionTreeDTO> regionTree() {
        // 查询所有区域数据
        List<RegionEntity> allRegions = regionRepository.selectAll();
        if (allRegions == null || allRegions.isEmpty()) {
            return Collections.emptyList();
        }

//        log.info("查询到{}条区域数据", allRegions.size());

        // 按省份分组
        Map<Long, List<RegionEntity>> provinceMap = allRegions.stream()
                .collect(Collectors.groupingBy(RegionEntity::getProvinceCode));

        // 构建省级树形结构
        List<RegionTreeDTO> result = new ArrayList<>();

        provinceMap.forEach((provinceCode, provinceList) -> {
            // 创建省级节点
            RegionTreeDTO provinceNode = new RegionTreeDTO();
            RegionEntity first = provinceList.get(0);
            provinceNode.setValue(String.valueOf(provinceCode));
            provinceNode.setLabel(first.getProvince());
            provinceNode.setChildren(new ArrayList<>());

            // 按城市分组
            Map<Long, List<RegionEntity>> cityMap = provinceList.stream()
                    .collect(Collectors.groupingBy(RegionEntity::getCityCode));

            // 构建市级节点
            cityMap.forEach((cityCode, cityList) -> {
                RegionTreeDTO cityNode = new RegionTreeDTO();
                RegionEntity cityFirst = cityList.get(0);
                cityNode.setValue(String.valueOf(cityCode));
                cityNode.setLabel(cityFirst.getCity());
                cityNode.setChildren(new ArrayList<>());

                // 添加区县节点
                for (RegionEntity district : cityList) {
                    RegionTreeDTO districtNode = new RegionTreeDTO();
                    districtNode.setValue(String.valueOf(district.getDistrictCode()));
                    districtNode.setLabel(district.getDistrict());
                    // 区县是最后一级，使用空列表而非null，避免JSON显示"children":null
                    districtNode.setChildren(Collections.emptyList());

                    cityNode.getChildren().add(districtNode);
                }

                provinceNode.getChildren().add(cityNode);
            });

            result.add(provinceNode);
        });

        // 对结果进行排序
        result.sort(Comparator.comparing(RegionTreeDTO::getValue));
        result.forEach(province -> {
            province.getChildren().sort(Comparator.comparing(RegionTreeDTO::getValue));
            province.getChildren().forEach(city -> {
                if (city.getChildren() != null && !city.getChildren().isEmpty()) {
                    city.getChildren().sort(Comparator.comparing(RegionTreeDTO::getValue));
                }
            });
        });

        return result;
    }

    @Override
    public RegionEntity getRegionByCode(Long code) {
        RegionQuery query = new RegionQuery();
        query.setDistrictCode(code);
        return regionRepository.selectOne(query);
    }
}
